package com.guoxin.part4.chapter16;

/**
 * @author guoxin
 * @date 2019/8/30
 */
public final class EatNoodleThreadImprove extends Thread {
    private final String name;
    private final TablewarePair tablewarePair;

    public EatNoodleThreadImprove(String name, TablewarePair tablewarePair) {
        this.name = name;
        this.tablewarePair = tablewarePair;
    }


    @Override public void run() {
        while (true) {
            eat();
        }
    }

    private void eat() {
        synchronized (tablewarePair) {
            System.out.println(
                    name + " take up " + tablewarePair.getLeftTool() +
                            "(left)");
            System.out.println(
                    name + " take up " + tablewarePair.getRightTool() +
                            "(right)");
            System.out.println(name + " is eating now");
            System.out.println(
                    name + " put down " + tablewarePair.getRightTool() +
                            "(right)");
            System.out.println(
                    name + " put down " + tablewarePair.getLeftTool() +
                            "(left)");
        }
    }

    public static void main(String[] args) {
        TablewarePair tablewarePair = new TablewarePair(new Tableware("fork"),
                new Tableware("knife"));
        new EatNoodleThreadImprove("A", tablewarePair).start();
        new EatNoodleThreadImprove("B", tablewarePair).start();
    }
}
